package com.example.springbootasyncdemo.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@ConfigurationProperties(prefix = "task-pool")
@Slf4j
@Data
public class TaskPoolConfig {
    private int coreSize;
    private int keepAlive;
    private int maxSize;
    private int queueCapacity;

    @Bean("asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        log.info("coreSize:{},keepAlive:{},maxSize:{},queueCapacity:{}", coreSize, keepAlive, maxSize, queueCapacity);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(coreSize);
        executor.setMaxPoolSize(maxSize);
        executor.setKeepAliveSeconds(keepAlive);
        executor.setQueueCapacity(queueCapacity);
        executor.setAwaitTerminationSeconds(60);
        executor.setThreadNamePrefix("my-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
